<?php

class Wlib_View_ResourceRenderer
{
    protected $_view = null;

    protected $_resourceObject = null;

    public function __construct($resourceObject)
    {
        $this->setResourceObject($resourceObject);
    }
    
    public function render()
    {
        $resourceObject = $this->getResourceObject();
        $filePath = $this->getTplPath($resourceObject);

        $dir = dirname($filePath);
        $file = basename($filePath);

        $this->getView()->addScriptPath($dir);
        $content = $this->getView()->render($file);

        return $content;
    }

    public function getTplPath($object)
    {
        if(is_object($object)) {
            $className = get_class($object);
        } else if(is_string($object)) {
            $className = $object;
        }

        $separator = '_';
        $classParts = explode($separator, $className);

        $filter = new Zend_Filter_Word_CamelCaseToDash();

        $module = strtolower($filter->filter(array_shift($classParts)));
        $fileName = strtolower($filter->filter(array_pop($classParts))) . '.phtml';

        $filePath = APPLICATION_PATH . '/modules/' . $module . '/views/resources/' ;

        foreach ($classParts as $oPart) {
            $filePath .= strtolower($filter->filter($oPart)) . '/';
        }

        $filePath .= $fileName;

        return $filePath;
    }

    public function assignViewVars($viewVars)
    {
        $this->getView()->assign($viewVars);
    }
    
    /**
     * @return Zend_View
     */
    public function getView()
    {
        if (null === $this->_view) {
            $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
            if (null === $viewRenderer->view) {
                $viewRenderer->initView();
            }
            $view = clone $viewRenderer->view;
            $view->clearVars();
            $view->setScriptPath(array());
            $this->setView($view);
        }

        return $this->_view;
    }

    public function setView($view)
    {
        $this->_view = $view;
        return $this;
    }

    public function getResourceObject()
    {
        return $this->_resourceObject;
    }

    public function setResourceObject($resourceObject)
    {
        $this->_resourceObject = $resourceObject;
        return $this;
    }
}